<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/3/28
 * Time: 2:59
 */

namespace App\Services;

use App\Exceptions\AlreadyExistException;
use App\Exceptions\BaseException;
use App\Exceptions\NotExistException;
use App\Models\Record as RecordModel;

class Record extends BaseService
{
    /**
     * 获取记录列表
     *
     * @param $limit
     * @param array $filter
     * @return mixed
     */
    public function getList($limit, $filter = [])
    {
        $records = RecordModel::select()->with('sku.product.category');
        if (isset($filter['name'])) {
            $name = $filter['name'];
            $records->whereHas('sku.product', function ($query) use ($name) {
                $query->where('name', 'like', "%{$name}%");
            });
        }
        if (isset($filter['sku_id'])) {
            $records->where('sku_id', $filter['sku_id']);
        }
        if (isset($filter['type'])) {
            $records->where('type', $filter['type']);
        }
        return $records->paginate($limit);
    }

    /**
     * 获取单个记录信息
     *
     * @param $id
     * @return mixed
     * @throws NotExistException
     */
    public function show($id)
    {
        $product = RecordModel::with('sku.product.category')->find($id);
        if (!$product) throw new NotExistException('记录不存在');
        return $product;
    }

    /**
     * 添加记录
     *
     * @param $data
     * @return static
     * @throws BaseException
     */
    public function create($data)
    {
        $sku = \App\Models\Sku::find($data['sku_id']);
        if($data['type'] == RecordModel::TYPE_IN){
            $sku->increment('quantity', $data['quantity']);
        }else{
            if($sku->quantity >= $data['quantity']){
                $sku->decrement('quantity', $data['quantity']);
            }else{
                throw new BaseException('库存量不够,出库失败!');
            }
        }
        return RecordModel::create($data);
    }

}